<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="供应商名称" prop="supplierName">
              <el-input v-model="queryParams.supplierName" placeholder="请输入供应商名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="工厂地点" prop="factoryLocation">
              <el-input v-model="queryParams.factoryLocation" placeholder="请输入工厂地点" clearable @keyup.enter="handleQuery" />
            </el-form-item>
         

            <el-form-item label="负责人" prop="responsiblePerson">
              <el-input v-model="queryParams.responsiblePerson" placeholder="请输入负责人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
           
            <el-form-item label="详细地址" prop="detailedAddress">
              <el-input v-model="queryParams.detailedAddress" placeholder="请输入详细地址" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            
            <el-form-item label="所在行业" prop="industry">
              <el-input v-model="queryParams.industry" placeholder="请输入所在行业" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registrationAddress">
              <el-input v-model="queryParams.registrationAddress" placeholder="请输入注册地址" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="资质名称" prop="qualificationName">
              <el-input v-model="queryParams.qualificationName" placeholder="请输入资质名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
      
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['supplier:supplier:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['supplier:supplier:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['supplier:supplier:remove']">删除</el-button>
          </el-col>
      <!--     <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['supplier:supplier:export']">导出</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="supplierList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="" align="center" prop="id" v-if="true" />
        <el-table-column label="供应商名称" align="center" prop="supplierName" />
        <el-table-column label="主要供货产品" align="center" prop="mainProducts" />
        <el-table-column label="工厂地点" align="center" prop="factoryLocation" />
  
        <el-table-column label="负责人" align="center" prop="responsiblePerson" />
        <el-table-column label="负责人联系电话" align="center" prop="responsiblePhone" />
        <el-table-column label="成立时间" align="center" prop="establishmentTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.establishmentTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看" placement="top">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['supplier:supplier:view']"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['supplier:supplier:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['supplier:supplier:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />

<!--       <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" /> -->
    </el-card>
    <!-- 添加或修改供应商对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="supplierFormRef" :model="form" :rules="rules"  label-width="120px">
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input v-model="form.supplierName" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item label="工厂地点" prop="factoryLocation">
          <el-input v-model="form.factoryLocation" placeholder="请输入工厂地点" />
        </el-form-item>
        <el-form-item label="注册资本" prop="registeredCapital">
          <el-input v-model="form.registeredCapital" placeholder="请输入注册资本" />
        </el-form-item>
        <el-form-item label="主要供货产品" prop="mainProducts">
          <el-input v-model="form.mainProducts" placeholder="请输入主要供货产品" />
        </el-form-item>
        <el-form-item label="合作模式" prop="cooperationMode">
          <el-input v-model="form.cooperationMode" placeholder="请输入合作模式" />
        </el-form-item>
        <el-form-item label="风机类型" prop="fanType">
          <el-input v-model="form.fanType" placeholder="请输入风机类型" />
        </el-form-item>
        <el-form-item label="企业属性" prop="enterpriseAttribute">
          <el-input v-model="form.enterpriseAttribute" placeholder="请输入企业属性" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="负责人" prop="responsiblePerson">
          <el-input v-model="form.responsiblePerson" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="负责人联系电话" prop="responsiblePhone">
          <el-input v-model="form.responsiblePhone" placeholder="请输入负责人联系电话" />
        </el-form-item>
        <el-form-item label="详细地址" prop="detailedAddress">
          <el-input v-model="form.detailedAddress" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="开票抬头" prop="invoiceHead">
          <el-input v-model="form.invoiceHead" placeholder="请输入开票抬头" />
        </el-form-item>
        <el-form-item label="单位税号" prop="unitTaxNumber">
          <el-input v-model="form.unitTaxNumber" placeholder="请输入单位税号" />
        </el-form-item>
        <el-form-item label="法人姓名" prop="legalPersonName">
          <el-input v-model="form.legalPersonName" placeholder="请输入法人姓名" />
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="unifiedSocialCreditCode">
          <el-input v-model="form.unifiedSocialCreditCode" placeholder="请输入统一社会信用代码" />
        </el-form-item>
        <el-form-item label="成立时间" prop="establishmentTime">
          <el-date-picker clearable
            v-model="form.establishmentTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择成立时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="所在行业" prop="industry">
          <el-input v-model="form.industry" placeholder="请输入所在行业" />
        </el-form-item>
        <el-form-item label="注册地址" prop="registrationAddress">
          <el-input v-model="form.registrationAddress" placeholder="请输入注册地址" />
        </el-form-item>
        <el-form-item label="资质名称" prop="qualificationName">
          <el-input v-model="form.qualificationName" placeholder="请输入资质名称" />
        </el-form-item>
        <el-form-item label="资质文件" prop="qualificationFile">
          <file-upload v-model="form.qualificationFile"/>
        </el-form-item>
        <el-form-item label="备注信息" prop="remarks">
            <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
<!-- 查看详情弹窗 -->
<el-dialog 
  :title="viewDialog.title" 
  v-model="viewDialog.visible" 
  width="800px"
  append-to-body>
  <el-descriptions :column="2" border>
    <el-descriptions-item label="供应商名称">{{ viewData.supplierName }}</el-descriptions-item>
    <el-descriptions-item label="工厂地点">{{ viewData.factoryLocation }}</el-descriptions-item>
    <el-descriptions-item label="注册资本">{{ viewData.registeredCapital }}</el-descriptions-item>
    <el-descriptions-item label="主要供货产品">{{ viewData.mainProducts }}</el-descriptions-item>
    <el-descriptions-item label="合作模式">{{ viewData.cooperationMode }}</el-descriptions-item>
    <el-descriptions-item label="风机类型">{{ viewData.fanType }}</el-descriptions-item>
    <el-descriptions-item label="企业属性">{{ viewData.enterpriseAttribute }}</el-descriptions-item>
    <el-descriptions-item label="联系人">{{ viewData.contactPerson }}</el-descriptions-item>
    <el-descriptions-item label="联系电话">{{ viewData.contactPhone }}</el-descriptions-item>
    <el-descriptions-item label="负责人">{{ viewData.responsiblePerson }}</el-descriptions-item>
    <el-descriptions-item label="负责人电话">{{ viewData.responsiblePhone }}</el-descriptions-item>
    <el-descriptions-item label="详细地址">{{ viewData.detailedAddress }}</el-descriptions-item>
    <el-descriptions-item label="开票抬头">{{ viewData.invoiceHead }}</el-descriptions-item>
    <el-descriptions-item label="单位税号">{{ viewData.unitTaxNumber }}</el-descriptions-item>
    <el-descriptions-item label="法人姓名">{{ viewData.legalPersonName }}</el-descriptions-item>
    <el-descriptions-item label="信用代码">{{ viewData.unifiedSocialCreditCode }}</el-descriptions-item>
    <el-descriptions-item label="成立时间">{{ parseTime(viewData.establishmentTime) }}</el-descriptions-item>
    <el-descriptions-item label="所在行业">{{ viewData.industry }}</el-descriptions-item>
    <el-descriptions-item label="注册地址">{{ viewData.registrationAddress }}</el-descriptions-item>
    <el-descriptions-item label="资质名称">{{ viewData.qualificationName }}</el-descriptions-item>
    <el-descriptions-item label="资质文件"><file-upload v-model="form.qualificationFile"  :disabled="true"/></el-descriptions-item>
    <el-descriptions-item label="备注信息" :span="2">{{ viewData.remarks || '无' }}</el-descriptions-item>
  </el-descriptions>
  <template #footer>
    <el-button @click="viewDialog.visible = false">关闭</el-button>
  </template>
</el-dialog>
  </div>
</template>

<script setup name="Supplier" lang="ts">
import { listSupplier, getSupplier, delSupplier, addSupplier, updateSupplier } from '@/api/supplier/supplier';
import { SupplierVO, SupplierQuery, SupplierForm } from '@/api/supplier/supplier/types';
import { propTypes } from '@/utils/propTypes';
import { useDisabled } from 'element-plus';
// 新增导入
import { listByIds } from '@/api/system/oss';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const supplierList = ref<SupplierVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRangeEstablishmentTime = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const supplierFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: SupplierForm = {
  id: undefined,
  supplierName: undefined,
  factoryLocation: undefined,
  registeredCapital: undefined,
  mainProducts: undefined,
  cooperationMode: undefined,
  fanType: undefined,
  enterpriseAttribute: undefined,
  contactPerson: undefined,
  contactPhone: undefined,
  responsiblePerson: undefined,
  responsiblePhone: undefined,
  detailedAddress: undefined,
  invoiceHead: undefined,
  unitTaxNumber: undefined,
  legalPersonName: undefined,
  unifiedSocialCreditCode: undefined,
  establishmentTime: undefined,
  industry: undefined,
  registrationAddress: undefined,
  qualificationName: undefined,
  qualificationFile: undefined,
  remarks: undefined
}
const data = reactive<PageData<SupplierForm, SupplierQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    supplierName: undefined,
    factoryLocation: undefined,
    registeredCapital: undefined,
    mainProducts: undefined,
    cooperationMode: undefined,
    fanType: undefined,
    enterpriseAttribute: undefined,
    contactPerson: undefined,
    contactPhone: undefined,
    responsiblePerson: undefined,
    responsiblePhone: undefined,
    detailedAddress: undefined,
    invoiceHead: undefined,
    unitTaxNumber: undefined,
    legalPersonName: undefined,
    unifiedSocialCreditCode: undefined,
    industry: undefined,
    registrationAddress: undefined,
    qualificationName: undefined,
    qualificationFile: undefined,
    remarks: undefined,
    params: {
      establishmentTime: undefined,
    }
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    supplierName: [
      { required: true, message: "供应商名称不能为空", trigger: "blur" }
    ],
    factoryLocation: [
      { required: true, message: "工厂地点不能为空", trigger: "blur" }
    ],
    mainProducts: [
      { required: true, message: "主要供货产品不能为空", trigger: "blur" }
    ],
    cooperationMode: [
      { required: true, message: "合作模式不能为空", trigger: "blur" }
    ],
    fanType: [
      { required: true, message: "风机类型不能为空", trigger: "change" }
    ],
    enterpriseAttribute: [
      { required: true, message: "企业属性不能为空", trigger: "blur" }
    ],
    contactPerson: [
      { required: true, message: "联系人不能为空", trigger: "blur" }
    ],
    contactPhone: [
      { required: true, message: "联系电话不能为空", trigger: "blur" }
    ],
    responsiblePerson: [
      { required: true, message: "负责人不能为空", trigger: "blur" }
    ],
    responsiblePhone: [
      { required: true, message: "负责人联系电话不能为空", trigger: "blur" }
    ],
    detailedAddress: [
      { required: true, message: "详细地址不能为空", trigger: "blur" }
    ],
    unitTaxNumber: [
      { required: true, message: "单位税号不能为空", trigger: "blur" }
    ],
    legalPersonName: [
      { required: true, message: "法人姓名不能为空", trigger: "blur" }
    ],
    unifiedSocialCreditCode: [
      { required: true, message: "统一社会信用代码不能为空", trigger: "blur" }
    ],
    industry: [
      { required: true, message: "所在行业不能为空", trigger: "blur" }
    ],
    registrationAddress: [
      { required: true, message: "注册地址不能为空", trigger: "blur" }
    ],
    qualificationName: [
      { required: true, message: "资质名称不能为空", trigger: "blur" }
    ],
    qualificationFile: [
      { required: true, message: "资质文件不能为空", trigger: "blur" }
    ],
  }
});
// 在data部分添加OSS数据类型
interface OssData {
  id: number;
  fileName: string;
  originalName: string;
  url: string;
  createTime: string;
}
const { queryParams, form, rules } = toRefs(data);
// 在现有代码的data/reactive部分添加：
const viewDialog = reactive({
  visible: false,
  title: '供应商详细信息'
});

const viewData = ref<SupplierVO>();
// 判断是否为图片
const isImage = (url: string) => {
  return /\.(jpg|jpeg|png|gif|webp)$/i.test(url);
};

// 查看详情方法
const handleView = async (row?: SupplierVO) => {
  const _id = row?.id || ids.value[0];
  const res = await getSupplier(_id);
  Object.assign(form.value, res.data);
  viewData.value = res.data;
  viewDialog.visible = true;

};

/** 查询供应商列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  proxy?.addDateRange(queryParams.value, dateRangeEstablishmentTime.value, 'EstablishmentTime');
  const res = await listSupplier(queryParams.value);
  supplierList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  supplierFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangeEstablishmentTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: SupplierVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加供应商";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: SupplierVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getSupplier(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改供应商";
}



/** 提交按钮 */
const submitForm = () => {
  supplierFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateSupplier(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addSupplier(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: SupplierVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除供应商编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delSupplier(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('supplier/supplier/export', {
    ...queryParams.value
  }, `supplier_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
<style scoped>
/* 详情弹窗样式优化 */
:deep(.el-descriptions__body) {
  background-color: #fafafa;
}
:deep(.el-descriptions__label) {
  width: 120px;
  font-weight: bold;
}
</style>
